package offer;

import java.util.Arrays;

/**
 * @author ZhanBo
 * @date 2020/6/20
 */
public class Solution29 {

    public static void main(String[] args) {
        int [][] array = {{1,2,3},{4,5,6},{7,8,9}};
        System.out.println(Arrays.toString(spiralOrder(array)));
    }

    /**
     * 剑指 Offer 29. 顺时针打印矩阵
     *输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
     *
     *输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
     * 输出：[1,2,3,6,9,8,7,4,5]
     *
     * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
     * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
     * @param matrix
     * @return
     */
    public static int[] spiralOrder(int[][] matrix) {
        if (matrix==null || matrix.length ==0){
            return new int[0];
        }
        int [] result = new int [matrix.length*matrix[0].length];
        //四个边界
        //上
        int on = 0;
        //下
        int down = matrix.length-1;
        //左
        int left = 0;
        //右
        int right = matrix[0].length-1;
        int resultIndex = 0;
        while (true){
            //从左至右
            for (int i = left ; i <= right ; i++ ){
                result[resultIndex++]  = matrix[on][i];
            }
            //上边界加1
            if (++on > down){
                break;
            }
            //从上之下
            for (int i = on; i <= down ; i++){
                result[resultIndex++] = matrix[i][right];
            }
            //右边界减1
            if (left>--right){
                break;
            }
            //从右至左
            for (int i = right; i >=left ; i--){
                result[resultIndex++] = matrix[down][i];
            }
            //下边界减1
            if (on>--down){
                break;
            }
            //从下之上
            for (int i = down ; i >= on ; i--){
                result[resultIndex++] = matrix[i][left];
            }
            //左边界加1
            if (++left > right){
                break;
            }
        }
        return result;
    }
}
